package org.sun.sunshine.io.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;

//udp server
public class DatagramChannelServerDemo {

    public static void main(String[] args) {
        udpServer();
    }

    public static void udpServer()
    {
        try(DatagramChannel datagramChannel=DatagramChannel.open();){
            datagramChannel.configureBlocking(false);
            datagramChannel.bind(new InetSocketAddress(9090));
            Selector selector=Selector.open();
            datagramChannel.register(selector, SelectionKey.OP_READ);

            //循环检查通道中是否有准备好的数据
            while(selector.select()>0){
                selector.selectedKeys().forEach(selectionKey -> {
                    if(selectionKey.isReadable()){
                        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                        try {
                            //注意这里是receive
                            datagramChannel.receive(byteBuffer);
                            //切换到读模式
                            byteBuffer.flip();
                            System.out.println(new String(byteBuffer.array(), 0,byteBuffer.limit()));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
